﻿using System;
using System.Collections.Generic;
using System.Linq;
using Luna.Data.Common;
using NUnit.Framework;

namespace Luna.Data.Test.Common
{
    public class TextSearchTest : EntityTest<ISearchProvider, ISearchData, Guid>
    {
        public TextSearchTest(string contextName)
            : base(contextName)
        {
        }

        public override Action<Guid> Delete
        {
            get { return Service.TextSearchDelete; }
        }

        public override Predicate<ISearchData> DeletePredicate
        {
            get { return x => x.DisplayName.StartsWith(DataManager.Generator.SeedString); }
        }

        public override Func<Guid, ISearchData> Get
        {
            get { return Service.TextSearchGet; }
        }

        public override Func<IEnumerable<ISearchData>> GetAll
        {
            get { return Service.TextSearchGetAll; }
        }

        public override Func<ISearchData, Guid> KeyGetter
        {
            get { return x => x.PK; }
        }

        public override Action<ISearchData> Save
        {
            get { return Service.TextSearchSave; }
        }

        protected override ISearchData Create()
        {
            var entity = Context.Get<ISearchData>();
            DataManager.Load(entity);
            return entity;
        }

        protected override bool AreSame(ISearchData data1, ISearchData data2)
        {
            return DataManager.AreSame(data1, data2);
        }

        [Test]
        public void TestSearch()
        {
            var entity = Create();
            entity.SearchField = entity.DisplayName + " tato";

            var entity2 = Create();
            entity2.SearchField = entity2.DisplayName + " tata";

            Save(entity);
            Save(entity2);

            var result1 = Service.TextSearch("ta", 2);
            Expect(result1.Count(), Is.EqualTo(2));

            var result2 = Service.TextSearch("ta", 1);
            Expect(result2.Count(), Is.EqualTo(1));

            var result3 = Service.TextSearch("tato", 2);
            Expect(result3.Count(), Is.EqualTo(1));
        }

        private string Reverse(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return token;
            }

            char[] array = token.ToCharArray();
            Array.Reverse(array);
            return new String(array);
        }
    }
}